use std::env;

use actix_session::storage::CookieSessionStore;
use actix_session::SessionMiddleware;
use actix_web::middleware::Logger;
use actix_web::{get, web, App, HttpServer};
use dotenv::dotenv;

// This struct represents state
struct AppState {
    app_name: String,
}

#[get("/")]
async fn index(data: web::Data<AppState>) -> String {
    let app_name = &data.app_name; // <- get app_name
    format!("Hello {app_name}!") // <- response with app_name
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {

    // Load environment variables from the .env file
    dotenv().ok();

    // Initializes the global logger with an env logger
    env_logger::init();

    // Generate the private key used for the identity service
    let private_key = actix_web::cookie::Key::generate();

    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(AppState {
                app_name: String::from("Actix Web"),
            }))
            .wrap(Logger::new(r#"%a "%r" %s [%Ts]"#))
            .wrap(SessionMiddleware::new(CookieSessionStore::default(), private_key.clone()))
            .service(index)
    })
    .bind(env::var("SERVER_URL").unwrap_or_else(|_| "127.0.0.1:8080".to_string()))?
    .workers(4)
    .run()
    .await
}
